﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace BCDto.Utils
{
    /// <summary>
    /// 图片类型验证
    /// </summary>
    public class ImageAttribute : ValidationAttribute
    {
        private string[] imageSuffixes = new string[] { "jpg", "jpeg", "png" };

        public ImageAttribute()
        {

        }
        public ImageAttribute(string[] imageSuffixes)
        {
            this.imageSuffixes = imageSuffixes;
        }

        public override bool IsValid(object value)
        {
            if (value is IList)
            {
                IList<string> list = value as IList<string>;
                for (int i=0;i< list.Count;i++)
                {
                    string vStr = list[i];
                    List<string> urls = new List<string>();
                    urls = vStr.IndexOf(',') > -1 ? vStr.Split(',').ToList() : new List<string> { vStr };

                    foreach (string url in urls)
                    {
                        if (!ValidationImageSuffix(url))
                        {
                            ErrorMessage = string.Format("{0} 是不被接收的图片类型,请重新上传.仅支持:{1}", url.Substring(url.LastIndexOf('.') + 1), string.Join(',', imageSuffixes));
                            return false;
                        }
                    }
                }
                return true;
            }
            else
            {
                if (value!=null)
                {
                    string vStr = value.ToString();
                    List<string> urls = new List<string>();
                    urls = vStr.IndexOf(',') > -1 ? vStr.Split(',').ToList() : new List<string> { vStr };

                    foreach (string url in urls)
                    {
                        if (!ValidationImageSuffix(url))
                        {
                            ErrorMessage = string.Format("{0} 是不被接收的图片类型,请重新上传.仅支持:{1}", url.Substring(url.LastIndexOf('.') + 1), string.Join(',', imageSuffixes));
                            return false;
                        }
                    }
                    return true;
                }
                else
                {
                    return true;
                }
            }
        }
        private bool ValidationImageSuffix(string imageUrl)
        {
            string suffix = imageUrl.Substring(imageUrl.LastIndexOf('.') + 1);
            return imageSuffixes.Contains(suffix);
        }
    }
}
